<script setup>
// 适用与后端需要所有选中（包含半选中）的id数组，且回显数据时的id数组与设置的id数组一致
defineProps({
    // 提示语
    placeholder: {
        type: String,
        default: '请选择',
    },
    collapseTags: {
        type: Boolean,
        default: true,
    },
    cascaderOptions: {
        type: Array,
        default: () => [],
    },
    cascaderProps: {
        type: Object,
        default: () => ({
            value: 'value',
            label: 'label',
            children: 'children',
            multiple: true, //多选
            checkStrictly: false, // 父子是否关联 false为关联 true为不关联
            expandTrigger: 'click',
            // true为返回由该节点所在的各级菜单的值所组成的数组 false只返回该节点的值
            emitPath: false,
        }),
    },
    clearable: {
        type: Boolean,
        default: true,
    },
    // 是否显示所有选项的完整路径
    showAllLevels: {
        type: Boolean,
        default: true,
    },
    // 是否可搜索
    filterable: {
        type: Boolean,
        default: false,
    },
    // 选中的id数组
    modelValue: {
        type: Array,
        default: () => [],
    },
    full: {
        type: Boolean,
        default: false,
    },
})

import { ref } from 'vue'
import { useHandleArray } from '@/composable/useHandleArray'
const { arrayDeduplication } = useHandleArray()

const selfCascaderSelect = ref(null)

const emit = defineEmits(['update:modelValue'])
// 返回选中的id（包含半选中的父节点）数组
const selectIds = () => {
    let checkedNodesArr = selfCascaderSelect.value.getCheckedNodes()
    let checkedIds = []
    checkedNodesArr.forEach(item => {
        let idsArr = getCheckIds(item)
        checkedIds = arrayDeduplication(idsArr, checkedIds)
    })
    emit('update:modelValue', checkedIds)
}

// 递归获取node及其父级的id
const getCheckIds = (node, checkedIds = []) => {
    checkedIds.push(node.value)
    if (node.parent) getCheckIds(node.parent, checkedIds)
    return checkedIds
}
</script>

<template>
    <el-cascader ref="selfCascaderSelect" :placeholder="placeholder" :collapse-tags="collapseTags"
        :model-value="modelValue" :show-all-levels="showAllLevels" :options="cascaderOptions" :props="cascaderProps"
        :clearable="clearable" :filterable="filterable" @change="selectIds" :class="[full ? 'full-box-class' : '']" />
</template>

<style scoped lang="scss">
.full-box-class {
    width: 100% !important;
}
</style>